#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct student	{
	int roll;
	char name[50];
	int marks;
}s;

FILE *openfile(char *name,char *mode)
{
	FILE *f;
	if((f=fopen(name,mode))==NULL)	{
		printf("\nFile open error.");
		getch();
		exit(1);
	}
	return f;
}

void create_db()
{
	char usr;
	FILE *f;
	f=openfile("sdb.dat","w");
	do	{
		printf("\nEnter roll number,name,marks:");
		scanf("%d%s%d",&s.roll,s.name,&s.marks);
		fprintf(f,"\n%d %s %d",s.roll,s.name,s.marks);
		printf("\nContinue(y/n)?:");
		usr=getche();
	} while(usr!='n' && usr!='N');
	fclose(f);
}

void display_db()
{
	FILE *f;
	f=openfile("sdb.dat","r");
	printf("\nNow displaying database:\nRoll\tName\tMarks");
	while(!feof(f))	{
		fscanf(f,"%d %s %d",&s.roll,s.name,&s.marks);
		printf("\n%d\t%s\t%d",s.roll,s.name,s.marks);
	}
	fclose(f);
}

void add_db()
{
	char usr;
	FILE *f;
	f=openfile("sdb.dat","a");
	do	{
		printf("\nEnter roll,name,marks:");
		scanf("%d %s %d",&s.roll,s.name,&s.marks);
		fprintf(f,"\n%d %s %d",s.roll,s.name,s.marks);
		printf("\nContinue(y/n)?:");
		usr=getche();
	} while(usr!='n' && usr!='N');
	fclose(f);
}

void delete_db()
{
	char usr;
	int r;
	FILE *f1,*f2;
	f1=openfile("sdb.dat","r");
	f2=openfile("sdb.tmp","w");
	printf("\nEnter roll number to be deleted:");
	scanf("%d",&r);
	while(!feof(f1))	{
		fscanf(f1,"%d %s %d",&s.roll,s.name,&s.marks);
		if(s.roll!=r)
			fprintf(f2,"\n%d %s %d",s.roll,s.name,s.marks);
	}
	fclose(f1);
	fclose(f2);
	remove("sdb.dat");
	rename("sdb.tmp","sdb.dat");
}

void main()
{
	create_db();
	display_db();
	delete_db();
	display_db();
	getch();
}